package com.u17;

/**
 * @author u17
 * https://leetcode-cn.com/problems/search-insert-position/
 */
public class Solution {

    /**
     * 使用折半查找
     * @param nums
     * @param target
     * @return
     */
    public int searchInsert(int[] nums, int target) {
        int start = 0;
        int end = nums.length - 1;
        int mid = 0;
        while (start <= end) {
            mid = (start + end) >> 1;
            if (target > nums[mid]) {
                start = mid + 1;
            } else if (target < nums[mid]) {
                end = mid - 1;
            } else if (target == nums[mid]) {
                return mid;
            }
        }
        if (end < mid) {
            return mid;
        } else {
            return mid + 1;
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] nums = new int[]{1, 3, 5, 6};
        int target = 2;
        System.out.println(solution.searchInsert(nums, target));
    }
}
